using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Audio;
using Microsoft.Xna.Framework.Content;
using Microsoft.Xna.Framework.GamerServices;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Input;
using Microsoft.Xna.Framework.Media;
using FUSE;


namespace FUSE
{
    /// <summary>
    /// This is the main type for your game
    /// </summary>
    public class FUSEgame : Microsoft.Xna.Framework.Game
    {
        //Thread thread;

        int currentScreen = MyConstants.ITitleScreen; // default 0 is titlescreen
        int oldScreen = MyConstants.ITitleScreen;

        Boolean tutorialMode = false;

        //Graphical declarations
        GraphicsDeviceManager graphics;
        private ContentManager contentManager;
        SpriteBatch spriteBatch;

        protected Song song;
        

        public Galaxy galaxyScreen;
        public TitleScreen titleScreen;


        
        //private Texture2D backgroundTexture, headTexture;

        //Game declarations
        private ShipFile shipsList;
        private Planet planet1;
        private int lastTickCount;
        private KeyboardState keyboard;
        private Player gamePlayer;
        private DemoMapGenerator demoMapGen;
        private MapGenerator mapGenerator;

        public FUSEgame()
        {
            graphics = new GraphicsDeviceManager(this);

            contentManager = new ContentManager(Services, "Content");
            Content.RootDirectory = "Content";
            //Debug view debugs our galaxy physics world


        }

        /// <summary>
        /// Allows the game to perform any initialization it needs to before starting to run.
        /// This is where it can query for any required services and load any non-graphic
        /// related content.  Calling base.Initialize will enumerate through any components
        /// and initialize them as well.
        /// </summary>
        protected override void Initialize()
        {
            //galaxy = new Galaxy(this);
            //galaxy.tInitialize();
            

            // TODO: Add your initialization logic here
            //TODO:Initialize sound here

            Window.Title = "FUSE Alpha Game";

            // load title screen            
            //titleScreen = new TitleScreen(graphics);
            //titleScreen.Initialize();

            //load creationscreen
            //creationScreen = new CreationScreen(graphics);
            //creationScreen.Initialize();

            base.Initialize();
        }
        /// <summary>
        /// 
        /// </summary>
        protected override void BeginRun()
        {
            //TODO: play the title sound here

            //TODO: Start the logo splash screen here
            //ChangeState(GameState.LogoSplash);

            //TODO:field of view
            //TODO: aspect ratio
            //TODO:near plane
            //TODO:farplane

            //TODO: initialize camera here
            //TODO: camera view position
            base.BeginRun();
        }

        /*
        private void LoadContentThread()
        {
            thread = new Thread(new ThreadStart(LoadContentHelper));
            thread.IsBackground = true;
            thread.Start();

            while (!thread.IsAlive) ;
        }
         * */

        private void LoadContentHelper()
        { 
          


            //Galaxy galaxy = new Galaxy(this);
            //galaxy.Initialize();

            //Components.Add(galaxy);

            

            /*
            int arraySize = 1;
            Texture2D[] planets = new Texture2D[arraySize];
            planets[0] = Content.Load<Texture2D>("Planet01Small");

            demoMapGen = new DemoMapGenerator(this);
            demoMapGen.Initialize();
            Map demoMap = demoMapGen.GenerateDemoMap(2);
            demoMap.galaxyForces = PhysicsEngine.createGravityGrid2(demoMap);

            PhysicsEngine.ToStringGalaxy(demoMap, false);

            Console.WriteLine(demoMap.ToString());
             */

            //Galaxy galaxy = new Galaxy();
            //Components.Add(galaxy);

        }
        

        /// <summary>
        /// LoadContent will be called once per game and is the place to load
        /// all of your content.
        /// </summary>
        protected override void LoadContent()
        {
            base.LoadContent();

            //TODO: load services
            // Create a new SpriteBatch, which can be used to draw textures.
            spriteBatch = new SpriteBatch(GraphicsDevice);
            
            Services.AddService(typeof(SpriteBatch), spriteBatch);
            Services.AddService(typeof(GraphicsDeviceManager), graphics);
            Services.AddService(typeof(ContentManager), contentManager);

            shipsList = new ShipFile();
            shipsList.LoadShipFile();
            Services.AddService(typeof(ShipFile), shipsList);

            demoMapGen = new DemoMapGenerator(this);
            demoMapGen.Initialize();
            Services.AddService(typeof(DemoMapGenerator), demoMapGen);

            mapGenerator = new MapGenerator(this);
            //mapGenerator.setDifficulty(MapGenerator.Difficulty.Insane);
            mapGenerator.Initialize();
            

            //Load music
            song = Content.Load<Song>("53576_newgrounds_guitar");
            MediaPlayer.Volume = MediaPlayer.Volume * 0.3f;
            MediaPlayer.IsRepeating = true;
            MediaPlayer.Play(song);
            //NOTE: galaxy background music should not be playing, 
            // should only play when galaxy is initialized, 
            Services.AddService(typeof(Song), song);



            //TODO: MapValidator Testing Code
            //Map demoMap = demoMapGen.GenerateDemoMap(0, 2);
            //demoMap.galaxyForces = PhysicsEngine.createGravityGrid2(demoMap);
            //(new MapValidator(demoMap)).Validate();

            //mapGenerator.ThreadedFunctions();
            //(new MapValidator(mapGenerator.getMap())).Validate();
             

            Services.AddService(typeof(MapGenerator), mapGenerator);

            Components.Add(mapGenerator);
            //Create player
            gamePlayer = new Player(this);
            
            //TODO: BUILD screen choose ship/player attributes

            

            Services.AddService(typeof(Player), gamePlayer);

            titleScreen = new TitleScreen(this);
            titleScreen.Initialize();
            
            titleScreen.Show();

            Components.Add(titleScreen);

            CreationScreen creation = new CreationScreen(this);
            
            creation.Initialize();
            creation.LoadContent(this.Content);
            creation.Enabled = false;
            creation.Visible = false;

            Services.AddService(typeof (CreationScreen), creation);

            Components.Add(creation);

            galaxyScreen = new Galaxy(this);
            //galaxy.Difficulty = MapGenerator.Difficulty.Medium;
            galaxyScreen.Initialize();
            galaxyScreen.Hide();

            Components.Add(galaxyScreen);

            //titleScreen.LoadContent(this.Content);
            //creationScreen.LoadContent(this.Content);

            

            //LoadContentThread();


            //gamePlayer.setPlayerConditions((int)gamePlayer.maxArmor, (int)gamePlayer.maxHealth, (int)gamePlayer.maxSpeed, (int)gamePlayer.maxFuel, 8);

            

            
            // TODO: use this.Content to load your game content here
        }

        /// <summary>
        /// UnloadContent will be called once per game and is the place to unload
        /// all content.
        /// </summary>
        protected override void UnloadContent()
        {
            // TODO: Unload any non ContentManager content here
        }
        Vector2 force = new Vector2(10, 10);
        
        /// <summary>
        /// Allows the game to run logic such as updating the world,
        /// checking for collisions, gathering input, and playing audio.
        /// </summary>
        /// <param name="gameTime">Provides a snapshot of timing values.</param>
        protected override void Update(GameTime gameTime)
        {

            


            //TODO: Add controls here 
            // Allows the game to exit
            /*if (GamePad.GetState(PlayerIndex.One).Buttons.Back == ButtonState.Pressed)
                this.Exit();

            //update screens
            if (currentScreen == MyConstants.ITitleScreen)
            {
                //titleScreen.Update(gameTime);
                //UpdateScreenSelection(titleScreen.ScreenSelection);
                foreach (TitleScreen item in Components.OfType<TitleScreen>())
                {
                    if (item.ScreenSelection != MyConstants.ITitleScreen)
                    {
                        UpdateScreenSelection(item.ScreenSelection, item);
                        item.ScreenSelection = MyConstants.ITitleScreen;
                    }
                    else
                    {
                        if (item.Enabled == false)
                        {
                            //item.Initialize(); <-- if called will break my style of screens
                            item.Enabled = true;
                            item.Visible = true;
                        }
                    }
                }
            }
            else if (currentScreen == MyConstants.ICreationScreen)
            {
                //creationScreen.Update(gameTime);
                //UpdateScreenSelection(creationScreen.ScreenSelection);
                foreach (CreationScreen item in Components.OfType<CreationScreen>())
                {
                    if (item.ScreenSelection != MyConstants.ICreationScreen)
                    {
                        UpdateScreenSelection(item.ScreenSelection, item);
                        item.ScreenSelection = MyConstants.ICreationScreen;
                    }
                    else
                    {
                        if (item.Enabled == false)
                        {
                            //item.Initialize(); <-- if called will break my style of screens
                            item.Enabled = true;
                            item.Visible = true;
                        }
                    }
                }
            }
            else if (currentScreen == MyConstants.GalaxyScreen)
            {
                foreach (Galaxy item in Components.OfType<Galaxy>())
                {
                    if (item.ScreenSelection != MyConstants.GalaxyScreen)
                    {
                        UpdateScreenSelection(item.ScreenSelection, item);
                        item.ScreenSelection = MyConstants.GalaxyScreen;
                    }
                    else
                    {
                        if (item.Enabled == false)
                        {
                            item.Initialize();
                            item.Enabled = true;
                            item.Visible = true;
                        }
                    }
                }
                
            }

            // TODO: Add your update logic here

            //mapGenerator.Update(gameTime);
            /*
            if (thread.IsAlive)
            {
                if (mapGenerator.mapList.Count < 1)
                {
                    thread.Suspend();
                }

                if (mapGenerator.mapList.Count >= 1 && thread.ThreadState == System.Threading.ThreadState.Suspended)
                {
                    thread.Resume();
                }

            }
            **/
            base.Update(gameTime);
        }

        /// <summary>
        /// This is called when the game should draw itself.
        /// </summary>
        /// <param name="gameTime">Provides a snapshot of timing values.</param>
        protected override void Draw(GameTime gameTime)
        {
            GraphicsDevice.Clear(Color.Black);


            // TODO: Add your drawing code here
            /*spriteBatch.Begin();

            //draw title screen
            //titleScreen.Draw();

            //draw current screen
            if (currentScreen == MyConstants.ITitleScreen)
            {
                //titleScreen.Draw();

                foreach (TitleScreen item in Components.OfType<TitleScreen>())
                {
                    if (item.ScreenSelection != MyConstants.ITitleScreen)
                    {

                        UpdateScreenSelection(item.ScreenSelection, item);
                        //item.Enabled = false;
                        item.ScreenSelection = MyConstants.ITitleScreen;
                    }
                    else
                    {
                        if (item.Enabled == false)
                        {
                            //item.Initialize(); <-- if called will break my style screens
                            item.Enabled = true;
                            item.Visible = true;
                        }
                    }
                }
            }
            else if (currentScreen == MyConstants.ICreationScreen)
            {
                //creationScreen.Draw();
                foreach (CreationScreen item in Components.OfType<CreationScreen>())
                {
                    if (item.ScreenSelection != MyConstants.ICreationScreen)
                    {
                        UpdateScreenSelection(item.ScreenSelection, item);
                        //item.Enabled = false;
                        item.ScreenSelection = MyConstants.ICreationScreen;
                    }
                    else
                    {
                        if (item.Enabled == false)
                        {
                            //item.Initialize(); <-- if called will break my style screens
                            item.Enabled = true;
                            item.Visible = true;
                        }
                    }
                }
            }
            else if (currentScreen == MyConstants.GalaxyScreen)
            {

                
                foreach (Galaxy item in Components.OfType<Galaxy>())
                {
                    if (item.ScreenSelection != MyConstants.GalaxyScreen)
                    {
                        UpdateScreenSelection(item.ScreenSelection, item);
                        //item.Enabled = false;
                        item.ScreenSelection = MyConstants.GalaxyScreen;
                    }
                    else
                    {
                        
                        
                        if (item.Enabled == false)
                        {
                            item.Initialize();
                            item.Enabled = true;
                            item.Visible = true;
                        }
                    }
                }
            }
        

            spriteBatch.End();*/

            base.Draw(gameTime);
        }

        // checks for screen change request and handles it
        private void UpdateScreenSelection(int screenNumberReturned, Object screen)
        {
            // if the screen number requested is different than the current screen number
            if (screenNumberReturned != currentScreen)
            {
                currentScreen = screenNumberReturned;

                if (screen is CreationScreen)
                {
                    ((CreationScreen)screen).ScreenSelection = MyConstants.ICreationScreen;
                }
                else if (screen is Galaxy)
                {
                    ((Galaxy)screen).ScreenSelection = MyConstants.GalaxyScreen;
                }
                else if (screen is TitleScreen)
                {
                    ((TitleScreen)screen).ScreenSelection = MyConstants.ITitleScreen;
                }
            }
        }
    }
}
